package global

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"miao-server/lib/db"
	"miao-server/lib/log"
	"miao-server/lib/utils"
	"miao-server/structs/base"
	"miao-server/structs/enum"
	"os"
	"path/filepath"
)

var (
	Conf = new(base.Config)
	DB   *gorm.DB
)

func InitConfig() (err error) {
	currentPath, err := os.Executable()
	if err != nil {
		err = errors.New(fmt.Sprintf("加载配置文件失败： %+v", err))
		return
	}
	v := viper.New()
	v.SetConfigType("yaml")
	v.SetConfigName("config")
	v.AddConfigPath(filepath.Dir(currentPath))
	err = v.ReadInConfig()
	if err != nil {
		err = errors.New(fmt.Sprintf("加载配置文件失败： %+v", err))
		return
	}
	err = v.Unmarshal(Conf)
	if err != nil {
		err = errors.New(fmt.Sprintf("不合法的配置信息：%+v", err))
		return
	}
	// 服务端代码不要放太多的默认配置，应该多读配置文件。默认配置越多，无意间带来的错误越多
	if Conf.Tcp.Server == "" {
		Conf.Tcp.Server = ":19004"
	}
	if Conf.Tcp.Interval == 0 {
		Conf.Tcp.Interval = enum.TcpHeartbeatInterval
	}
	if Conf.Http.PluginFolder == "" {
		Conf.Http.PluginFolder = enum.PluginFolder
		err = utils.CreateFolder(Conf.Http.PluginFolder)
		if err != nil {
			return
		}
	}
	log.InitLog(Conf.Log.Name, Conf.Log.Lv)
	return
}

func InitDb() {
	var err error
	DB, err = db.GetDB(Conf.DB.Supper, Conf.DB.ShowSqlLog, Conf.DB.Source)
	if err != nil {
		logrus.Panicf("连接数据库失败：%v", err)
	}
	autoMigrate()
}
